SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE FUNCTION [Live].[GetInstrumentSortOrder]
(
	-- Add the parameters for the function here
	@ExportId INT,
	@AssetIntrnlId INT 
)
RETURNS INT
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ReturnVal VARCHAR(150)

	-- Add the T-SQL statements to compute the return value here
	SELECT 
		@ReturnVal = CASE WHEN a.AssetType <> 'Instrument' THEN 90 + id.SortOrder 
			ELSE id.SortOrder
			END 
	
	
	 FROM  FSFundModel.Reporting.Asset a 
	INNER JOIN  FSFundModel.Reporting.Instrument i 
	ON a.InstrumentId =i.InstrumentId 
	AND i.ExportId = a.ExportId 
	INNER JOIN  FSFundModel.Reporting.InstrumentDefinition id
	ON id.ExportId = a.ExportId 
	AND i.InstDefId = id.InstDefId



	WHERE a.ExportId = @ExportId
	AND a.AssetIntrnlId= @AssetIntrnlId

	-- Return the result of the function
	RETURN @ReturnVal

END
GO
EXEC sp_addextendedproperty N'VirtualFolder', N'Live', 'SCHEMA', N'Live', 'FUNCTION', N'GetInstrumentSortOrder', NULL, NULL
GO
